package org.ohos.sample.cordova;

import com.ffsky.litepack.logger.L;
import com.ffsky.litepack.util.StringCompat;
import ohos.agp.components.webengine.*;
import ohos.agp.utils.TextTool;
import ohos.app.Context;
import ohos.global.resource.Resource;
import ohos.media.image.PixelMap;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;

public class SystemWebAgent extends WebAgent {
    String TAG = "SystemWebAgent";
    protected WebViewInterface webViewInterface;
    private String pageLoadedUrl;
    public SystemWebAgent(WebViewInterface webViewInterface) {
        super();
        this.webViewInterface = webViewInterface;
    }
    @Override
    public void onLoadingPage(WebView webView, String url, PixelMap icon) {
        super.onLoadingPage(webView, url, icon);
        L.i(TAG,"onLoadingPage");
        // 页面开始加载时自定义处理
        if(webViewInterface!=null){
            webViewInterface.showWebViewLoading();
        }
    }

    @Override
    public void onPageLoaded(WebView webView, String url) {
        super.onPageLoaded(webView, url);
        pageLoadedUrl = url;
        L.i(TAG,"onPageLoaded");
        // 页面加载结束后自定义处理
        if(webViewInterface!=null){
            webViewInterface.hideWebViewLoading();
            webViewInterface.onWebViewPageFinished();
        }
    }

    @Override
    public void onError(WebView webView, ResourceRequest request, ResourceError error) {
        super.onError(webView, request, error);
        // 发生错误时自定义处理
        String url = request.getRequestUrl().toString();
        String err = error.toString();
        L.i(TAG,StringCompat.string("onError->url",url," err=",err));
    }

    @Override
    public void onLoadingContent(WebView webView, String url) {
        super.onLoadingContent(webView, url);
        // 加载资源时自定义处理
    }

    @Override
    public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
        if (request == null || request.getRequestUrl() == null) {
            L.i(TAG,"WebAgent isNeedLoadUrl:request is null.");
            return false;
        }
        String url = request.getRequestUrl().toString();
        if (url.startsWith("http:") || url.startsWith("https:")) {
            webView.load(url);
            return false;
        } else {
            return super.isNeedLoadUrl(webView, request);
        }
    }
    @Override
    public ResourceResponse processResourceRequest(WebView webView, ResourceRequest request) {
        final String authority = "example.com";
        final String rawFile = "/rawfile/";
        final String local = "/local/";
        Uri requestUri = request.getRequestUrl();
        String url = requestUri.toString();
        L.i(TAG, StringCompat.string("processResourceRequest->Uri=",url));
        if (authority.equals(requestUri.getDecodedAuthority())) {
            String path = requestUri.getDecodedPath();
            if (TextTool.isNullOrEmpty(path)) {
                return super.processResourceRequest(webView, request);
            }
            if (path.startsWith(rawFile)) {
                // 根据自定义规则访问资源文件
                String rawFilePath = "entry/resources/rawfile/" + path.replace(rawFile, "");
                String mimeType = URLConnection.guessContentTypeFromName(rawFilePath);
                L.i(TAG,StringCompat.string("processResourceRequest->rawFilePath=",rawFilePath));
                try {
                    final Context context = webView.getContext();
                    Resource resource = context.getResourceManager().getRawFileEntry(rawFilePath).openRawFile();
                    ResourceResponse response = new ResourceResponse(mimeType, resource, null);
                    return response;
                } catch (IOException e) {
                    L.i(TAG, "open raw file failed");
                }
            }
            if (path.startsWith(local)) {
                // 根据自定义规则访问本地文件
                final Context context = webView.getContext();
                String localFile = context.getFilesDir() + path.replace(local, "/");
                L.i(TAG, "open local file " + localFile);
                File file = new File(localFile);
                if (!file.exists()) {
                    L.i(TAG, "file not exists");
                    return super.processResourceRequest(webView, request);
                }
                String mimeType = URLConnection.guessContentTypeFromName(localFile);
                try {
                    InputStream inputStream = new FileInputStream(file);
                    ResourceResponse response = new ResourceResponse(mimeType, inputStream, null);
                    return response;
                } catch (IOException e) {
                    L.i(TAG, "open local file failed");
                }
            }
        }
        return super.processResourceRequest(webView, request);
    }

    public String getPageLoadedUrl() {
        return pageLoadedUrl;
    }
}
